package com.niit.web.controller;

import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.niit.service.UserService;
import com.niit.service.impl.UserServiceImpl;
import com.niit.utils.WebKit;

@WebServlet("/SendCodeController")
public class SendCodeController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String mobile = request.getParameter("mobile");
		UserService us = new UserServiceImpl();
		if(us.isMobExist(mobile)){
			response.getOutputStream().write("0".getBytes());//手机已注册
			return;
		}
		String key = "e6c5917c6d316ad27b10c37ddba8bf6b";//appkey
		String code = WebKit.getRandom();//产生的6位随机验证码
		request.getSession().setAttribute("code", code);//将验证码存入到session
		String value = URLEncoder.encode("#app#=求知&#code#="+code,"UTF-8");
		//接口请求地址
		String uri = "http://v.juhe.cn/sms/send?mobile="+mobile+"&tpl_id=1001&tpl_value="+value+"&key="+key;
		URL url = new URL(uri);
		url.openStream();
		response.getOutputStream().write("1".getBytes());//验证码发送成功
	}

}
